<template>
  <MoreInfo>
    <p>cannon - 物理引擎</p>
    <p>
      文档地址：
      <el-link
        href="https://pmndrs.github.io/cannon-es/docs/index.html"
        type="primary"
        target="_blank"
      >https://pmndrs.github.io/cannon-es/docs/index.html</el-link
      >
    </p>
    <p>流程：</p>
    <p>1.初始化物理世界</p>
    <HighlightJS :code="code1" />
    <p>2.创建几何体的同时，也创建物理世界几何体</p>
    <HighlightJS :code="code2" />
    <p>3.同步物理世界和 Three.js 场景</p>
    <HighlightJS :code="code3" />

  </MoreInfo>
</template>

<script setup>
import HighlightJS from '@/components/HighlightJS.vue'
import MoreInfo from '@/components/MoreInfo.vue'

const code1 = `
  const initPhysics = (CANNON) => {
    world.value = new CANNON.World()
    world.value.gravity.set(0, -9.82, 0) // 设置重力
    world.value.broadphase = new CANNON.NaiveBroadphase() // 碰撞检测算法
    world.value.solver.iterations = 10
    return world.value
  }
`

const code2 = `
  // 初始化物理世界
  initPhysics(CANNON)

  // 创建球体几何体和材质
  const sphereGeometry = new SphereGeometry(0.5, 32, 32)
  const sphereMaterial = new MeshNormalMaterial()

  // 创建 Three.js 球体网格
  sphereMesh = new Mesh(sphereGeometry, sphereMaterial)
  sphereMesh.position.set(0, 5, 0)
  scene.value.add(sphereMesh)

  // 创建物理球体
  sphereBody = new CANNON.Body({
    mass: 1,
    position: new CANNON.Vec3(0, 5, 0),
    shape: new CANNON.Sphere(0.5)
  })
  world.value.addBody(sphereBody)

  // 创建平面几何体和材质
  const planeGeometry = new PlaneGeometry(10, 10)
  const planeMaterial = new MeshStandardMaterial({
    color: 0xffffff,
    side: DoubleSide
  })

  // 创建 Three.js 平面网格
  planeMesh = new Mesh(planeGeometry, planeMaterial)
  planeMesh.rotation.x = -Math.PI / 2
  scene.value.add(planeMesh)

  // 创建物理平面
  planeBody = new CANNON.Body({
    mass: 0, // 质量为 0，表示静止不动
    shape: new CANNON.Plane()
  })
  planeBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) // 旋转至水平
  world.value.addBody(planeBody)
`

const code3 = `
  // 更新物理世界
  if(world.value) {
    world.value.step(1 / 60, delta, 3)
  }

  if (sphereMesh && sphereBody) {
    sphereMesh.position.copy(sphereBody.position)
    sphereMesh.quaternion.copy(sphereBody.quaternion)
  }
`
</script>
